package cn.stephen.study.demoproject.controller;

import cn.stephen.study.demoproject.entity.Report;
import cn.stephen.study.demoproject.service.ReportService;
import cn.stephen.study.demoproject.util.PageUtil;
import com.alibaba.fastjson.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.support.HttpRequestHandlerServlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/report")
public class ReportController {

    @Autowired
    private ReportService reportService;

    /**
     * 按条件查询
     */
    @RequestMapping("findByValues")
    @ResponseBody
    public JSONObject findByValues(@RequestParam("type") Integer type,
                                   @RequestParam("startTime") String startTime,
                                   @RequestParam("endTime") String endTime,
                                   @RequestParam("page") Integer page,
                                   @RequestParam("limit") Integer limit) {
        JSONObject jo = new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            List<Report> allByValue = reportService.findAllByValue(type, startTime, endTime);
            List<Report> reportList = PageUtil.listPaging(allByValue, page, limit);
            JSONArray jsonArray = new JSONArray();
            for (Report report : reportList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", report.getId());
                jsonObject.put("time", sdf.format(report.getTime()));
                jsonObject.put("type", report.getType());
                jsonObject.put("path", report.getPath());
                jsonArray.add(jsonObject);
            }
            jo.put("data", jsonArray);
            jo.put("total", allByValue == null ? 0 : allByValue.size());
            jo.put("code", 0);
            jo.put("msg", "查询成功");
        } catch (Exception e) {
            e.printStackTrace();
            jo.put("data", null);
            jo.put("total", 10);
            jo.put("code", 0);
            jo.put("msg", "");
        }
        return jo;
    }

    /**
     * 下载
     */
    @RequestMapping("expol")
    @ResponseBody
    public void findByValues(HttpServletRequest request, HttpServletResponse response, String id) {

        OutputStream os = null;
        try {
            String path = "D:\\tool\\baobiao\\" + reportService.findById(id);
//            String path="D:\\tool\\baobiao\\aaaa.doc";
            File file = new File(path);
            String fileName = file.getName();
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
            String agent = (String) request.getHeader("USER-AGENT"); //判断浏览器类型
            if (agent != null && agent.indexOf("Fireforx") != -1) {
                fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");   //UTF-8编码，防止输出文件名乱码
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            BufferedInputStream bis = null;
            response.reset();
            response.setCharacterEncoding("utf-8");
            if (ext.equals("doc") || ext.equals("docx")) {
                response.setContentType("application/msword"); // word格式
            } else if (ext.equals("pdf")) {
                response.setContentType("application/pdf"); // word格式
            }
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            bis = new BufferedInputStream(new FileInputStream(file));
            byte[] b = new byte[bis.available() + 1000];
            int i = 0;
            os = response.getOutputStream();   //直接下载导出
            while ((i = bis.read(b)) != -1) {
                os.write(b, 0, i);
            }
            os.flush();
            os.close();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
